import logging
import os
import time

from selenium.webdriver.support.wait import WebDriverWait

from config.config import BASE_DIR
from selenium.webdriver import ActionChains


class Base:

    # 初始化方法
    def __init__(self, driver):
        logging.info("正在初始化，driver对象：{}".format(driver))
        self.driver = driver

    # 查找元素方法
    def base_find(self, loc, timeout=10, poll=0.5):
        logging.info("正在查找元素：{}".format(loc))
        return WebDriverWait(self.driver, timeout, poll).until(lambda x: x.find_element(*loc))

    # 点击方法
    def base_click(self, loc):
        logging.info("正调用点击元素：{}".format(loc))
        self.base_find(loc).click()

    # 输入方法
    def base_input(self, loc, value):
        logging.info("正调用输入元素方法：{} 输入内容：{}".format(loc,value))
        # 获取元素
        el = self.base_find(loc)
        # 清空
        el.clear()
        # 输入
        el.send_keys(value)

    # 获取文本方法
    def base_get_text(self, loc):
        logging.info("正调用获取元素信息方法：{}".format(loc))
        return self.base_find(loc).text

    # 截图方法
    def base_get_img(self):
        logging.info("正调用截图方法")
        img_path = BASE_DIR + os.sep + "img" + os.sep + "{}.png".format(time.strftime("%Y%m%d%H%M%S"))
        self.driver.get_screenshot_as_file(img_path)

    # 切换frame
    def base_switch_frame(self, loc):
        logging.info("正在调用切换frame方法，切换对象：{}".format(loc))
        # 获取元素
        el = self.base_find(loc)
        # 执行切换
        self.driver.switch_to.frame(el)

    # 恢复frame
    def base_default_frame(self):
        self.driver.switch_to.default_content()

    # 拖动SeekBar方法
    def base_drag_seekbar(self, loc, offset_x, offset_y=0):
        """
        拖动SeekBar到指定位置
        :param loc: SeekBar元素定位方式
        :param offset_x: X轴偏移量
        :param offset_y: Y轴偏移量，默认为0
        """
        logging.info("正在拖动SeekBar元素：{}，X轴偏移量：{}，Y轴偏移量：{}".format(loc, offset_x, offset_y))
        # 获取SeekBar元素
        seekbar = self.base_find(loc)
        # 获取SeekBar的起始位置
        start_x = seekbar.location['x']
        start_y = seekbar.location['y']
        # 获取SeekBar的尺寸
        width = seekbar.size['width']
        height = seekbar.size['height']
        # 计算中心点位置
        center_x = start_x + width // 2
        center_y = start_y + height // 2
        # 执行拖动操作
        actions = ActionChains(self.driver)
        actions.click_and_hold(seekbar).move_by_offset(offset_x, offset_y).release().perform()